<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>流程图示例</title>
    <!-- 引入Mermaid库 -->
    <script src="js/mermaid/v11.3.0/mermaid.js"></script>
</head>
<body>
<div id="chart" class="mermaid"></div>

<script>
    // 初始化Mermaid
    mermaid.initialize({ startOnLoad: true });

    // 定义JSON数据和转换函数
    function jsonToMermaid(jsonData) {
        const nodes = jsonData.graph.nodes;
        const edges = jsonData.graph.edges;

        let mermaidCode = 'flowchart TD\n'; // 使用流图

        // 添加节点
        nodes.forEach(node => {
            if (node.shape === "circle") {
                mermaidCode += `  ${node.id}@{ shape: circle, label: "${node.label}" }\n`;
            } else if(node.shape === "dbl-circ"){
                mermaidCode += `  ${node.id}@{ shape: dbl-circ, label: "${node.label}" }\n`;
            }else {
                mermaidCode += `  ${node.id}[${node.label}] \n`;
            }
        });

        // 添加边
        edges.forEach(edge => {
            if (edge.label) {
                mermaidCode += `  ${edge.from} -->|${edge.label}| ${edge.to} \n`;
            } else {
                mermaidCode += `  ${edge.from} --> ${edge.to} \n`;
            }
        });

        return mermaidCode;
    }

    // JSON数据
    const jsonData = {
        "graph": {
            "nodes": [
                { "id": "A", "label": "开始", "shape": "circle" },
                { "id": "B", "label": "步骤1" },
                { "id": "C", "label": "步骤2" },
                { "id": "D", "label": "结束", "shape": "dbl-circ" }
            ],
            "edges": [
                { "from": "A", "to": "B", "label": "初始化" },
                { "from": "B", "to": "C", "label": "处理数据" },
                { "from": "C", "to": "B", "label": "返回" },
                { "from": "C", "to": "D", "label": "完成" }
            ]
        }
    };

    // 将JSON数据转换为Mermaid语法
    const mermaidCode = jsonToMermaid(jsonData);
    console.log(mermaidCode);
    // 确保文档完全加载后再设置innerHTML
    document.addEventListener('DOMContentLoaded', function() {
        document.getElementById('chart').innerHTML = mermaidCode;
    });
</script>
</body>
</html>